﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.AdminAnulaciones;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using System.Text;
using MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls;
using System.Collections.Generic;
using MS.InformationManagement.Support;

namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public partial class AnularRadicado : BaseControl, IAdminAnulacionesView
    {

        #region fields

        private AdminAnulacionesPresenter _presenter;

        #endregion

        #region Properties

        public List<SPListItem> items { get; set; }
        public Guid SourceList
        {
            get { return new Guid(Page.Request.QueryString["lstID"]); }
        }
        public int PageIndex
        {
            get
            {
                return pgrTemplates.PageIndex;
            }
            set
            {
                pgrTemplates.PageIndex = value;
            }
        }
        public int PageSize
        {
            get
            {
                return pgrTemplates.PageSize;
            }
            set
            {
                pgrTemplates.PageSize = value;
            }
        }
        public int TotalRecords
        {
            get
            {
                return pgrTemplates.TotalRecords;
            }
            set
            {
                pgrTemplates.TotalRecords = value;
            }
        }

        #endregion

        #region Form Events

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterAjaxLoaderPlugin();
            _presenter = new AdminAnulacionesPresenter(this);
            pgrTemplates.OnPageChanged += new Pager.PageChangeHandler(pgrTemplates_OnPageChanged);
            //pgrTemplates.NextLinkText = ">>";
            //pgrTemplates.PreviousLinkText = "<<";
            pgrTemplates.NumberOfPagesToDisplay = 10;
            PageIndex = 0;
            PageSize = 10;
            pgrTemplates.BuildPager();
            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadGridView();
        }

        protected void gvUsuarios_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

        }

        protected void gvUsuarios_RowCreated(object sender, GridViewRowEventArgs e)
        {
            try
            {
                e.Row.Cells[0].Visible = false;
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    SPListItem item = (SPListItem)e.Row.DataItem;
                    SPList listUser = SPContext.Current.Web.Lists[item[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_LIST_TARGET] + ""];
                    int idItemRadicado = int.Parse(item[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_ID_RADICADO_INTERNO] + "");
                    SPListItem itemRadicado = listUser.GetItemById(idItemRadicado);

                    Label lblGenerado = e.Row.FindControl("lblGenerado") as Label;
                    if (lblGenerado != null)
                        lblGenerado.Text = new SPFieldUserValue(SPContext.Current.Web, item[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_USER].ToString()).User.LoginName + "";

                    Label lblDepartamento = e.Row.FindControl("lblDepartamento") as Label;
                    if (lblDepartamento != null)
                        lblDepartamento.Text = item[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_DEPARTAMENTO] + "";

                    Label lblObservacion = e.Row.FindControl("lblObservacion") as Label;
                    if (lblObservacion != null)
                        lblObservacion.Text = item[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_OBSERVACIONES] + "";

                    HyperLink lblRadicado = e.Row.FindControl("HyperLinkID") as HyperLink;
                    if (lblRadicado != null)
                    { lblRadicado.NavigateUrl = SPContext.Current.Web.Url + "/_layouts/MS.InformationManagement.WP/" + GetCurrentPage(itemRadicado.ContentType.Name) + "?strategy=edit&List=" + itemRadicado.ParentList.ID + "&ID=" + itemRadicado.ID; lblRadicado.Text = item[CustomSiteColumns.FIELD_SOLICITUD_ANULACION_ID_RADICADO] + ""; }

                    Label lblDiasSolicitud = e.Row.FindControl("lblDiasSolicitud") as Label;
                    if (lblDiasSolicitud != null)
                        lblDiasSolicitud.Text = diferenciaFechas(item[SPBuiltInFieldId.Created].ToString()) + "";

                    ImageButton btnAnular = e.Row.FindControl("btnAnular") as ImageButton;
                    if (btnAnular != null)
                    {
                        btnAnular.ID = "btnAnular_" + e.Row.DataItemIndex;
                        btnAnular.Click += new ImageClickEventHandler(btnAnular_Click);
                    }

                    ImageButton bntRechazar = e.Row.FindControl("bntRechazar") as ImageButton;
                    if (bntRechazar != null)
                    {
                        bntRechazar.ID = "bntRechazar_" + e.Row.DataItemIndex;
                        bntRechazar.Click += new ImageClickEventHandler(bntRechazar_Click);
                    }
                }

            }
            catch (Exception ex)
            {
                this.HandleError(ex);
            }
        }

        void bntRechazar_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            GridViewRow row = (GridViewRow)btn.NamingContainer;
            DesplegarVentanaModal(SPContext.Current.Web.Url + "/_layouts/MS.InformationManagement.WP/AnulacionRadicado.aspx?strategy=rechazar&ID=" + row.Cells[0].Text, "Sistema de Gestión Documental", 600, 260, this.Page);
        }

        void btnAnular_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            GridViewRow row = (GridViewRow)btn.NamingContainer;
            DesplegarVentanaModal(SPContext.Current.Web.Url + "/_layouts/MS.InformationManagement.WP/AnulacionRadicado.aspx?strategy=anular&ID=" + row.Cells[0].Text, "Sistema de Gestión Documental", 600, 260, this.Page);
        }

        void pgrTemplates_OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            _presenter.HandleLoad();
            pgrTemplates.BuildPager();
        }

        public void DesplegarVentanaModal(string Url, string Titulo, Int32 ancho, Int32 alto, Page pagina)
        {
            StringBuilder scriptModal = new StringBuilder();
            scriptModal.Append("var showMyModalDialog = function() { var options = { ");
            scriptModal.Append("url : '");
            scriptModal.Append(Url);
            scriptModal.Append("', ");
            scriptModal.Append("title: '");
            scriptModal.Append(Titulo);
            scriptModal.Append("', width: ");
            scriptModal.Append(ancho.ToString());
            scriptModal.Append(", height: ");
            scriptModal.Append(alto.ToString());
            scriptModal.Append(", dialogReturnValueCallback: onDialogClose }; SP.UI.ModalDialog.commonModalDialogOpen(" + "'" + Url + "'" + ",options, onDialogClose, null); }; ");
            scriptModal.Append("function onDialogClose(dialogResult, returnValue) { ");
            scriptModal.Append("if (dialogResult == SP.UI.DialogResult.OK) { ");
            scriptModal.Append(" SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK); } ");
            scriptModal.Append(" } ");

            pagina.ClientScript.RegisterClientScriptBlock(pagina.GetType(), "Mensaje", scriptModal.ToString(), true);
            pagina.ClientScript.RegisterStartupScript(typeof(Page), "Precarga", "ExecuteOrDelayUntilScriptLoaded(showMyModalDialog, 'sp.ui.dialog.js');", true);
        }

        private SPUser GetUser(SPListItem item, SPField userField)
        {
            string currentValue = item[userField.Title].ToString();
            SPFieldUser field = (SPFieldUser)userField;
            SPFieldUserValue fieldValue = (SPFieldUserValue)field.GetFieldValue(currentValue);
            return fieldValue.User;

        }

        private string GetCurrentPage(string ContentTypeName)
        {
            string ResultPage = string.Empty;
            switch (ContentTypeName)
            {
                case GlobalConstants.CTTN_RADICADO_INTERNO:
                    ResultPage = "RadicadoInterno.aspx";
                    break;
                case GlobalConstants.CTTN_RADICADO_PERSONA:
                    ResultPage = "InsertarRadicado.aspx";
                    break;
                case GlobalConstants.CTTN_RADICADO_EMPRESA:
                    ResultPage = "InsertarRadicado.aspx";
                    break;
                case GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA:
                    ResultPage = "InsertarRadicadoSalida.aspx";
                    break;
                case GlobalConstants.CTTN_RADICADO_EMPRESA_SALIDA:
                    ResultPage = "InsertarRadicadoSalida.aspx";
                    break;
                default:
                    break;
            }
            return ResultPage;
        }

        public void LoadGridView()
        {
            _presenter.HandleLoad();
            pgrTemplates.BuildPager();
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {
            gvUsuarios.DataSource = items;
            gvUsuarios.DataBind();
            LoadControl();
        }

        private int diferenciaFechas(string dateTime)
        {
            DateTime oldDate = DateTime.Parse(dateTime);
            DateTime newDate = DateTime.Now;

            // Difference in days, hours, and minutes.
            TimeSpan ts = newDate - oldDate;

            // Difference in days.
            return ts.Days;
        }

        #endregion

        #region private methods

        private void LoadControl()
        {
            AdminAnulaciones pd = (AdminAnulaciones)this.Parent.Parent;
            if (pd != null)
            {
                if(items != null)
                    pd.SetPendientesAnular(items.Count);
                else
                    pd.SetPendientesAnular(0);
            }
        }

        #endregion
    }
}
